#include<iostream>
#include<string>
#include<vector>
#include<pthread.h>
#include<unistd.h>
using namespace std;

pthread_mutex_t gmutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t gcond = PTHREAD_COND_INITIALIZER;
void* MasterCode(void *args)//线程函数
{
    sleep(1);
    cout<<"主线程开始工作..."<<endl;
    string name = static_cast<const char*>(args);
    while(true)
    {
        int n = pthread_cond_signal(&gcond);
        if(n == 0)
        {
            sleep(1);
            cout<<"主线程唤醒一个线程..."<<endl;
        }

    }
}
void* SlaverCode(void *args)
{
    string name = static_cast<const char*>(args);
    while(true)
    {
        
        //1.加锁
        pthread_mutex_lock(&gmutex);
        //2.条件变量是在加锁和解锁之间使用的 
        pthread_cond_wait(&gcond,&gmutex);//阻塞等待主线程来唤醒
        //走到这说明此线程已经被主线程唤醒了 
        cout<<"被唤醒的线程是:"<<name<<endl;

        //解锁
        pthread_mutex_unlock(&gmutex);
    }
}




void StartMaster(std::vector<pthread_t> *tidsptr)
{
    pthread_t tid;
    int n = pthread_create(&tid,nullptr,MasterCode,(void*)"Master Thread");
    if(n == 0)
    {
        std::cout<<"主线程创建成功"<<std::endl;
        tidsptr->emplace_back(tid);
    }
}
void StartSlaver(std::vector<pthread_t> *tidsptr,int thraednum)
{
    for(int i=0;i<thraednum;i++)
    {
        char *name = new char[64];
        snprintf(name,64,"Slaver-%d",i+1);
        pthread_t tid;
        int n = pthread_create(&tid,nullptr,SlaverCode,(void*)name);
        if(n == 0)
        {
            std::cout<<"新线程创建成功："<<name<<std::endl;
            tidsptr->emplace_back(tid);
        }
    }
}

void WaitThread(std::vector<pthread_t> &tids)//等待线程
{
    for(auto &tid:tids)
    {
        pthread_join(tid,nullptr);
    }
}


int main()
{
    std::vector<pthread_t> tids;//vector中放tid
    StartMaster(&tids);//主线程开启(创建)
    StartSlaver(&tids,4);//被控制线程(创建)
    WaitThread(tids);
    return 0;
}